


$(function () {

    class Cart {
        constructor() {
            this.data = JSON.parse(localStorage.getItem("cart"))
            this.listInputState = []
            this.count_data = []
            this.all = []
            this.res = 0
            this.count = 0
            this.all_input = true
            this.calculate()
            this.render()
            this.resRender()
            this.bindEvent()

        }
        bindEvent() {
            var _this = this
            // 点击列表的input渲染底部结算部分
            $("#list-render").on("click", ".inp input", a => {
                this.countCalculate()
                this.resRender()
                this.allInput()
            })
            // 点击全选
            $(".all").on("click", ".check input", a => {
                console.log(1);
                if ($(".check input")[0].checked === true) {
                    this.addChecked()
                    this.countCalculate()
                    this.resRender()
                    document.querySelector("#checkbox").checked = true
                } else {
                    this.cancelChecked()
                    this.countCalculate()
                    this.resRender()
                }
            })
            // 底部全选
            $(".payment").on("click", ".quan input", a => {
                if ($(".quan input")[0].checked === true) {
                    this.addChecked()
                    this.countCalculate()
                    this.resRender()
                    document.querySelector("#checkbox").checked = true
                } else {
                    this.cancelChecked()
                    this.countCalculate()
                    this.resRender()

                }
            })
            // 删除当前
            $(".delete").each((index, ele) => {
                on(ele, "click", a => {
                    this.checkedDel(index)
                    this.calculate()
                    this.listInput( index )
                    this.render()
                    this.countCalculate()
                    this.allInput()
                    this.resRender()
                    this.bindEvent()
                })
            })
            // add reduce 添加/删除数量
            $(".add").each((index, ele) => {
                on(ele, "click", a => {
                    this.addCount(index)
                    this.calculate()
                    this.countCalculate()
                    this.listInput()
                    this.render()
                    this.resRender()
                    this.bindEvent()
                })
            })
            $(".reduce").each((index, ele) => {
                on(ele, "click", a => {
                    this.reduceCount(index)
                    this.calculate()
                    this.countCalculate()
                    this.listInput()
                    this.render()
                    this.resRender()
                    this.bindEvent()
                })
            })
            $(".num").each((index, ele) => {
                on(ele, "blur", a => {
                    console.log(111);
                    
                    this.count = ele.value
                    this.changeCount(index)
                    this.calculate()
                    this.countCalculate()
                    this.listInput()
                    this.render()
                    this.resRender()
                    this.bindEvent()
                })
            })
        }

        // add reduce按钮添加/减少count
        addCount(index) {
            // 存入数据
            var cart_data = this.data[index]
            cart_data.count++
            // 判断session Storage中有没有这个数据  有的话只改变数量
            if (this.data) {
                for (var i = 0; i < this.data.length; i++) {
                    if (cart_data.productId === this.data[i].productId) {
                        this.data[i].count = cart_data.count
                        sessionStorage.setItem("cart", JSON.stringify(this.data))
                        return;
                    }
                }
            } else { this.data = [] }
            // 没有的话直接存入
            this.data.push(cart_data)
            sessionStorage.setItem("cart", JSON.stringify(this.data))
            // 更新数据
            this.data = JSON.parse(sessionStorage.getItem("cart"))
        }
        reduceCount(index) {
            // 存入数据
            var cart_data = this.data[index]
            cart_data.count--
            if (cart_data.count < 1) cart_data.count = 1

            // 判断session Storage中有没有这个数据  有的话只改变数量
            if (this.data) {
                for (var i = 0; i < this.data.length; i++) {
                    if (cart_data.productId === this.data[i].productId) {
                        this.data[i].count = cart_data.count
                        sessionStorage.setItem("cart", JSON.stringify(this.data))
                        return;
                    }
                }
            } else { this.data = [] }
            // 没有的话直接存入
            this.data.push(cart_data)
            sessionStorage.setItem("cart", JSON.stringify(this.data))
            this.data = JSON.parse(sessionStorage.getItem("cart"))
        }

        // input键入count
        changeCount(index) {
            var cart_data = this.data[index]
            cart_data.count = parseInt(this.count)
            if (cart_data.count < 1) cart_data.count = 1

            // 判断session Storage中有没有这个数据  有的话只改变数量
            if (this.data) {
                for (var i = 0; i < this.data.length; i++) {
                    if (cart_data.productId === this.data[i].productId) {
                        this.data[i].count = cart_data.count
                        sessionStorage.setItem("cart", JSON.stringify(this.data))
                        return;
                    }
                }
            } else { this.data = [] }
            // 没有的话直接存入
            this.data.push(cart_data)
            sessionStorage.setItem("cart", JSON.stringify(this.data))
            this.data = JSON.parse(sessionStorage.getItem("cart"))
        }

        // 存储数据 后半功能（暂时不用后期优化用）
        saveData() {
            if (this.data) {
                for (var i = 0; i < this.data.length; i++) {
                    if (cart_data.productId === this.data[i].productId) {
                        this.data[i].count = cart_data.count
                        sessionStorage.setItem("cart", JSON.stringify(this.data))
                        return;
                    }
                }
            } else { this.data = [] }
            // 没有的话直接存入
            this.data.push(cart_data)
            sessionStorage.setItem("cart", JSON.stringify(this.data))
            // 更新数据
            this.data = JSON.parse(sessionStorage.getItem("cart"))
        }

        // 存储list input的状态(inp input)
        listInput( i ) {
            this.listInputState = []
            $(".inp input").each((index, ele) => {
                if (ele.checked) {
                    this.listInputState.push("checked")
                } else {
                    this.listInputState.push(" ")
                }
                if( index === i ){
                    this.listInputState.splice( index , 1 )
                }
            })
            console.log(this.listInputState);
            
        }

        // 删除当前商品
        checkedDel(index) {
            this.data.splice(index, 1)
            sessionStorage.removeItem("cart")
            sessionStorage.setItem("cart", JSON.stringify(this.data))
            // sessionStorage.
        }

        // 解决 全选之后jQuery不能取消和添加check 的BUG
        cancelChecked() {
            $(".inp input").each((index, ele) => {
                ele.checked = false
            })
            document.querySelector("#checkbox").checked = false
            document.querySelector(".check input").checked = false
        }
        addChecked() {
            $(".inp input").each((index, ele) => {
                ele.checked = true
            })
            $(".check input")[0].checked = true
        }

        // 全选反选 被点亮 
        allInput() {
            var all_input_count = 0
            $(".inp input").each((index, ele) => {
                if ($(".inp input")[index].checked) {
                    all_input_count++
                    return
                }
                this.all_input = false
            })
            // 判断checked的input是否等于data长度
            if (all_input_count === this.data.length) {
                this.all_input = true
            }

            console.log(this.all_input);

            if (this.all_input) {
                $(".quan input")[0].checked = true
                $(".check input")[0].checked = true
            } else {
                $(".quan input")[0].checked = false
                $(".check input")[0].checked = false
            }
        }
        // 计算器（小计）
        calculate() {
            this.all = []
            var res = 0
            for (var i = 0; i < this.data.length; i++) {
                res = this.data[i].count * this.data[i].price
                this.all.push(res)
            }
        }
        // 计算器（数量 总价）
        countCalculate( ) {
            this.count = 0
            this.res = 0
            this.listInputState
            $(".inp input").each((index, ele) => {
                if ($(".inp input")[index].checked == true) {
                    this.count += parseInt(this.data[index].count)
                    this.res += this.data[index].count * this.data[index].price
                }
            })

        }
        render() {
            var html = ''
            for (var i = 0; i < this.data.length; i++) {
                html += `
                <div class="commodity">
                    <div class="inp">
                        <input type="checkbox" ${this.listInputState[i]} >
                    </div>
                    <div class="information">
                        <div class="img">
                            <a href="http://localhost:3000/dist/detail.html">
                                <img src="${this.data[i].imgSrc}" alt="">
                            </a>
                        </div>
                        <ul>
                            <li class="title">
                                <div class="title-up">${this.data[i].title}</div>
                                <div class="down">黑色</div>
                            </li>
                            <li class="price">
                                <div class="price-up">￥ ${this.data[i].price}</div>
                                <s>￥ ${this.data[i].repricer}</s>
                            </li>
                            <li class="count">
                                <div class="add">+</div>
                                <input type="text" name="" class="num" value="${this.data[i].count}">
                                <div class="reduce">-</div>
                            </li>
                            <li class="cost">
                                <div class="cost-up">￥${this.all[i]}.00</div>
                                <div class="cost-down">省 ￥0.00</div>
                            </li>
                            <li class="del"><dt class="delete">删除</dt></li>
                        </ul>
                    </div>
                </div>`
            }
            $("#list-render").html(html)
        }
        resRender() {

            var html = `
            <div class="checkbox">
                <div class="quan">
                    <input type="checkbox" name="" id="checkbox">
                    全选
                </div>
                <div class="all-del">删除</div>
            </div>
            <div class="pay">立即结算</div>
            <div class="full">
                <div class="zj">总价:<span>￥ ${this.res}.00</span></div>
                <div class="select">已选择<span>${this.count}</span>件商品，优惠：<b> ¥ 0.00</b></div>
            </div>`
            $(".payment").html(html)
        }
    }




    new Cart()



})